package com.dailywork.basepro.thread;

import java.util.concurrent.*;

/**
 * 线程的取消和关闭
 *
 * @author think
 * @version 1.0.0
 * @since 2020/4/26
 */
public class FutureCancel {
    public static void timeRun(Runnable runnable, Long timeout, TimeUnit timeUnit) throws InterruptedException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future<?> future = executorService.submit(runnable);
        try {
            future.get(timeout, timeUnit);
        } catch (ExecutionException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            future.cancel(true);
        }
    }
}